package jamdodge.app;

import jamdodge.*;
import android.app.*;
import android.content.Context;
import android.location.*;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.webkit.*;

public class MainScreen extends Activity implements LocationListener {
    public static final String APP_NAME = "JamDodge";
	
	private WebView _webView;
	private static final String MAP_URL = "http://jam-dodge.enox.co.za/map.php"; //"http://gmaps-samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html"
	private static final String MAP_UPDATE = "javascript:onUpdate()";
	private boolean _canUpdateWV = false;
	
	private Location _location;
	
	private static final int DIALOG_USERID = 0;
	private static final int DIALOG_INFO = 1;
	
	private UserID _userID;
	
	public UserID GetUserID()
	{
		return _userID;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        _userID = new UserID(this);
        
        SetupLocationListener();
        Log.i(APP_NAME, "Location: Set up successfully.");
        
        SetupWebView();
        Log.i(APP_NAME, "WebView: Set up successfully.");
        
        SetupJavaScriptInterface();
        Log.i(APP_NAME, "WebView: Javascript interface is set up successfully.");
    }
    
    private void SetupLocationListener()
	{
		LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    	
		Criteria criteria = new Criteria();
    	criteria.setAccuracy(Criteria.ACCURACY_FINE);
    	String provider = locationManager.getBestProvider(criteria, true);
    	
    	Log.i(APP_NAME, "Location: Using provider " + provider);
    	
    	locationManager.requestLocationUpdates(provider, 5000, 0, this);

    	//immediately get some sort of position
    	_location = locationManager.getLastKnownLocation(provider);
	}
    
    /**
     * Sets up the WebView component on the layout.
     */
    private void SetupWebView()
    {
    	_webView = (WebView)findViewById(R.id.webView);
    	
        _webView.getSettings().setJavaScriptEnabled(true);
        _webView.getSettings().setDomStorageEnabled(true);
        _webView.getSettings().setAppCacheMaxSize(1024*1024*8); //8MB
        _webView.getSettings().setAppCachePath("/data/data/com.jamdodge.app/cache");
        _webView.getSettings().setAllowFileAccess(true);
        _webView.getSettings().setAppCacheEnabled(true);
        
        _webView.setWebViewClient(new WebViewClient(){
        	
        	@Override
        	public void onPageFinished(WebView view, String url)
        	{
        		_canUpdateWV = true;
        		Log.i(APP_NAME, "WebView: Finished loading map.");
        	}
        	
        });
   
        _webView.loadUrl(MAP_URL);
        Log.i(APP_NAME, "WebView: Loading map URL " + MAP_URL);
    }
    
    private void WebJavascriptUpdate()
    { 
    	_webView.loadUrl(MAP_UPDATE);
    }
    
    /**
     * Creates an interface to the web page javascript called 'window.android',
     * which can be used to get device details such as it's location.
     */
    private void SetupJavaScriptInterface()
    {
    	_webView.addJavascriptInterface(new JavaScriptInterface(), "android");
    }
    
    /**
     * @author Mitchell Cox
     * Provides methods for a javascript interface to this device via a web page.
     */
    private class JavaScriptInterface
    {
    	public double getLatitude()
    	{
    		return _location.getLatitude();
    	}
    	
    	public double getLongitude()
    	{
    		return _location.getLongitude();
    	}
    	
    	public float getSpeed()
    	{
    		return _location.getSpeed();
    	}
    	
    	public float getBearing()
    	{
    		return _location.getBearing();
    	}
    	
    	public String getUserID()
    	{
    		return _userID.GetUserID();
    	}
    }
    
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.mainmenu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch (item.getItemId())
    	{
    	case R.id.exit:
    		this.finish();
    		return true;
    	case R.id.viewinfo:
    		showDialog(DIALOG_INFO);
    		return true;
    	case R.id.viewid:
    		showDialog(DIALOG_USERID);
    		return true;
    	default:
    		return super.onOptionsItemSelected(item);
    	}
    }

    
    protected Dialog onCreateDialog(int id)
    {
    	switch (id)
    	{
    	case DIALOG_USERID:
    		return CreateUserIDDialog();
    	case DIALOG_INFO:
    		return CreateInfoDialog();    		
    	default:
    		return null;
    	}
    }
    
    /**
     * Creates the user ID dialog for this instance.
     */
    private Dialog CreateUserIDDialog()
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	 	
    	builder.setMessage(_userID.GetUserID());
    	builder.setCancelable(true);
    	
    	return (Dialog)builder.create();    	
    }

    private Dialog CreateInfoDialog()
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	
    	String info;
    	info = "Lat: " + Double.toString(_location.getLatitude()) + "\n";
    	info += "Long: " + Double.toString(_location.getLongitude()) + "\n";
    	info += "Speed: " + Float.toString(_location.getSpeed()) + " m/s\n";
    	info += "Bearing: " + Float.toString(_location.getBearing()) + " deg";
    	
    	builder.setMessage(info);
    	builder.setCancelable(true);
    	
    	return (Dialog)builder.create();
    }
    
    
    
    //Location event stuff: -----------------------------------------------------
    
	@Override
	public void onLocationChanged(Location loc) 
	{
		_location = loc;
		
		if (_canUpdateWV == true)
		{
			WebJavascriptUpdate();
		}
		
		Log.v(APP_NAME, "Location: New " + loc.getLatitude() + " " + loc.getLongitude() + " " + loc.getSpeed());
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}

   
}